package pl.nazaweb.imedproplus.business.service;

import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import pl.nazaweb.imedproplus.model.entity.DictionaryDefinition;
import pl.nazaweb.imedproplus.model.entity.DictionaryEntryDTO;
import pl.nazaweb.imedproplus.model.facade.DictionaryDefinitionFacade;

@Stateless
@LocalBean
public class DictionaryService {
    @EJB
    private DictionaryDefinitionFacade dictionaryDefinitionFacade;
    
    public List<DictionaryEntryDTO> getDictionaryValues(Long dictionaryId){
        DictionaryDefinition dictionaryDefinition = 
                this.dictionaryDefinitionFacade.getDictionaryDefinitionById(dictionaryId);
        String query = this.getDictionarySelectQuery(dictionaryDefinition);
        return this.dictionaryDefinitionFacade.getDictionaryEntries(query);
    }
    
    private String getDictionarySelectQuery(DictionaryDefinition def){
        StringBuilder query = new StringBuilder();
        query.append("select d.")
                .append(def.getNameColumn())
                .append(" as label, d.")
                .append(def.getValueColumn())
                .append(" as value from ")
                .append(def.getTableName())
                .append(" d ");
        if(def.getWhereCriteria()!=null){
            query.append(" where ").append(def.getWhereCriteria());
        }
        return query.toString();
    }
}
